package com.sunshine.demo.aspect;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * @author: sanglei
 * @date: 2018-11-01 14:45
 * @description:
 */
public class SpelParser {
    private static ExpressionParser parser = new SpelExpressionParser();

    public static String getValue(String key,String[] paramNames,Object[] args){
        Expression expression = parser.parseExpression(key);
        EvaluationContext context = new StandardEvaluationContext();
        if(args.length<=0){
            return null;
        }
        for(int i=0;i<args.length;i++){
            context.setVariable(paramNames[i],args[i]);
        }
        return expression.getValue(context,String.class);
    }

    public static void main(String[] args) {
        String key = "#id+' '+#usercode";
        String id = "112";
        String usercode = "ssss";
        String[] paramNames = new String[]{"id","usercode"};
        Object[] objects = new Object[2];
        objects[0] = id;
        objects[1]= usercode;
        System.out.println(SpelParser.getValue(key,paramNames,objects));
    }
}
